<!--
 * @Author: Mark
 * @Date: 2019-02-01 11:31:29
 * @LastEditors: Mark
 * @LastEditTime: 2019-02-11 15:28:50
 * @Description: 我的账单页面
 -->
<template>
  <div>
    <!-- <my-header></my-header> -->
    <div class="account-body">

      <el-row style="text-align:left">
        <date-time-picker
          class="accout-time-picker"
          @change="searchTimeChange"
          style="float:left"
        ></date-time-picker>
        <el-button
          type="primary"
          @click="getAccountListBySearchTime"
          icon="el-icon-search"
          style="margin-left:20px"
        > 搜索</el-button>
      </el-row>

      <el-row>
        <breadcrumb class="bread">
          <span slot="message">数据统计</span>
        </breadcrumb>
      </el-row>

      <el-row class="card">
        <el-col :span="6">
          <card :data='page.totalCard'></card>
        </el-col>
        <el-col :span="6">
          <card :data='page.payCard'></card>
        </el-col>
        <el-col :span="6">
          <card :data='page.unpayCard'></card>
        </el-col>
        <el-col :span="6">
          <card :data='page.quantityCard'></card>
        </el-col>
      </el-row>

      <breadcrumb class="bread">
        <span slot="message">表格展示</span>
      </breadcrumb>

      <el-row style="float:left;margin-top:-30px;margin-bottom:5px">
        <el-button
          type="primary"
          @click="dialogFormVisible = true"
        >添加账单</el-button>
        <el-button
          type="primary"
          @click="dialogFormNotGoodsVisible = true ;dialogFormNotGoodsAddFlag=  true"
        >快速记账</el-button>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-table
            :data="data.accountTableData"
            style="width: 100%"
            stripe
          >
            <el-table-column
              prop="createTime"
              label="时间"
              width="110"
            >
            </el-table-column>
            <el-table-column
              prop="goodsName"
              label="零件"
              width="200"
            >
            </el-table-column>

            <el-table-column
              label="图片"
              width="150"
            >
              <template slot-scope="scope">
                <img
                  style="width:50px;height:50px"
                  v-if="scope.row.imgAddr == null"
                  src="../../../static/images/bill/notGoods.png"
                >
                <img
                  style="width:50px;height:50px"
                  v-else
                  v-lazy="scope.row.imgAddr"
                >
              </template>
            </el-table-column>

            <el-table-column
              prop="goodsCategoryName"
              label="所属种类"
              width="200"
            >
            </el-table-column>

            <el-table-column
              prop="price"
              label="单价（元）"
            >
            </el-table-column>

            <el-table-column
              prop="quantity"
              label="数量（件）"
            >
            </el-table-column>

            <el-table-column
              prop="totalPrice"
              label="总额（元）"
            >
            </el-table-column>

            <el-table-column
              prop="enableStatus"
              label="状态"
            >
            </el-table-column>

            <el-table-column
              prop="paymentTime"
              label="支付时间"
            >
            </el-table-column>

            <el-table-column
              prop="description"
              label="描述"
            >
            </el-table-column>

            <el-table-column
              fixed="right"
              label="操作"
              width="250"
            >
              <template slot-scope="scope">
                <el-button-group>
                  <el-button
                    type="primary"
                    icon="el-icon-edit" 
                    size="small"
                    @click="editNotGoods(scope.row)"
                  ></el-button>

                  <el-button
                    type="danger"
                    size="small"
                    @click="deleteAccount(scope.row)"
                    icon="el-icon-delete" 
                  ></el-button>
                </el-button-group>

              </template>
            </el-table-column>

          </el-table>
        </el-col>
      </el-row>
      <el-pagination
        v-if="data.accountTableData.length>0"
        class="pagination-content"
        small
        layout="prev,pager, next"
        :total="page.total"
        :page-size="page.pageSize"
        @prev-click="clickProPre"
        @next-click="clickProNext"
        @current-change="clickProPage"
      >
      </el-pagination>

      <!-- 新增账单记录弹出窗口 -->
      <el-dialog
        title="新增账单"
        :visible.sync="dialogFormVisible"
        class="dialog"
      >
        <el-form
          :model="form"
          label-width="80px"
          :rules="AccoutFromRules"
          ref="ruleForm"
        >
          <el-form-item label="时间">
            <date-picker @change="change"></date-picker>
          </el-form-item>

          <el-form-item
            label="零件"
            prop="goodsId"
          >
            <el-select
              v-model="form.goodsId"
              placeholder="请选择加工零件"
            >
              <el-option
                v-for="item in data.selectData"
                :key="item.id"
                :label="item.name"
                :value="item.value"
              ></el-option>

            </el-select>
          </el-form-item>

          <el-form-item label="数量">
            <el-input-number
              class="account-quantity"
              v-model="form.quantity"
              size="medium"
              :min="1"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="付款">
            <el-switch
              class="paymentSate"
              style="display: block"
              v-model="form.state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-text="已结算"
              inactive-text="未结算"
            >
            </el-switch>
          </el-form-item>

          <el-form-item label="描述">
            <el-input
              type="textarea"
              v-model="form.desc"
            ></el-input>
          </el-form-item>
        </el-form>

        <div
          slot="footer"
          class="dialog-footer"
        >
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="submit('ruleForm')"
          >确 定</el-button>
        </div>
      </el-dialog>

      <!-- 新增账单记录弹出窗口（无需选择商品的形式） -->
      <el-dialog
        :title="dialogFormNotGoodsTitle"
        :visible.sync="dialogFormNotGoodsVisible"
        class="dialog"
      >
        <el-form
          :model="form"
          label-width="80px"
          :rules="AccoutFromRules"
          ref="ruleForm"
        >
          <el-form-item label="时间">
            <date-picker @change="change"></date-picker>
          </el-form-item>

          <el-form-item label="单价(元)">
            <el-input-number
              style="width:217px"
              class="price"
              v-model="form.price"
              size="medium"
              :precision="2"
              :step="0.01"
              :min="0.01"
            ></el-input-number>
          </el-form-item>

          <el-form-item label="数量">
            <el-input-number
              class="account-quantity"
              v-model="form.quantity"
              size="medium"
              :min="1"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="付款">
            <el-switch
              class="paymentSate"
              style="display: block"
              v-model="form.state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-text="已结算"
              inactive-text="未结算"
            >
            </el-switch>
          </el-form-item>

          <el-form-item label="描述">
            <el-input
              type="textarea"
              v-model="form.desc"
            ></el-input>
          </el-form-item>
        </el-form>

        <div
          slot="footer"
          class="dialog-footer"
        >
          <el-button @click="dialogFormNotGoodsVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="submitNotGoods('ruleForm')"
          >确 定</el-button>
        </div>
      </el-dialog>

      <!-- 趋势图 -->
      <el-row>
        <breadcrumb class="bread">
          <span slot="message">趋势图</span>
        </breadcrumb>
      </el-row>
      <el-row style="margin-bottom:20px">
        <el-button-group>
          <el-button
            @click="getLineData(true)"
            size="mini"
            round
            type="primary"
            :autofocus='1==1'
          >金额</el-button>
          <el-button
            @click="getLineData(false)"
            type="primary"
            size="mini"
            round
          >数量</el-button>
        </el-button-group>
      </el-row>

      <el-row>
        <div
          id="line"
          style="width: 100%;height:400px;"
        >
          暂无数据
        </div>
      </el-row>

    </div>
  </div>
</template>

<script>
import LineChart from "@/components/myChart/LineChart";
import MyHeader from "@/components/Header";
import Breadcrumb from "@/components/Breadcrumb";
import DatePicker from "@/components/DatePicker";
import DateTimePicker from "@/components/DateTimePicker";
import Card from "@/components/Card";

import GoodsService from "@/service/bill/goods-service";
const _goods = new GoodsService();
import Tips from "@/utils/tipsUtil";
const _tips = new Tips();
import Account from "@/service/bill/account-service";
const _account = new Account();

export default {
  data() {
    return {
      page: {
        timestamps: [],
        pageNum: 1, //当前的页数
        pageSize: 10, //页面大小
        total: "", //总的条数
        totalCard: {
          title: "总额（元）",
          content: 0, //
          color: "#DCDFE6"
        },
        payCard: {
          title: "已结算总额（元）",
          content: 0, //
          color: "#E4E7ED"
        },
        unpayCard: {
          title: "未结算总额（元）",
          content: 0, //
          color: "#EBEEF5"
        },
        quantityCard: {
          title: "总加工零件数（件）",
          content: 0, //
          color: "#F2F6FC"
        }
      },

      data: {
        selectData: Object,
        accountTableData: new Array()
      },
      dialogFormVisible: false,
      //无需选择商品的弹出框
      dialogFormNotGoodsVisible: false,
      //无需选择商品的弹出框的标题
      dialogFormNotGoodsTitle: "快速记账",
      dialogFormNotGoodsAddFlag: true,
      form: {
        id: "",
        time: "",
        state: false,
        goodsId: "",
        price: "",
        quantity: "",
        desc: ""
      },
      AccoutFromRules: {
        goodsId: [
          { required: true, message: "请选择加工零件", trigger: "blur" }
        ]
      }
    };
  },

  components: {
    MyHeader,
    Breadcrumb,
    DatePicker,
    DateTimePicker,
    Card
  },

  computed: {},

  mounted() {
    this.init();
  },

  methods: {
    /**
     * 初始化默认为今天
     */
    init() {
      this.value = new Date();
      let vue = this;
      _goods.getOptionInfo().then(res => {
        vue.data.selectData = res.data;
      });
      this.getAccountListBySearchTime();
      this.getStatisticalInfo();
      //趋势图
      this.getLineData(true);
    },

    /**
     * 时间控件发生改变的事件
     */
    change(data) {
      this.form.time = data;
    },

    searchTimeChange(data) {
      this.page.timestamps = data;
    },

    submit(form) {
      const vue = this;
      this.$refs[form].validate(valid => {
        if (valid) {
          const requestParam = {
            createTime: vue.form.time,
            fkGoodsId: vue.form.goodsId,
            quantity: vue.form.quantity,
            enableStatus: vue.form.state == true ? 2 : 1,
            description: vue.form.desc
          };
          _account.addAccount(requestParam).then(
            res => {
              _tips.notifyTips(vue, res.msg);
            },
            err => {
              _tips.notifyTips(vue, err.msg);
            }
          );
        }
      });
    },

    submitNotGoods(form) {
      const vue = this;
      this.$refs[form].validate(valid => {
        if (valid) {
          const requestParam = {
            createTime: vue.form.time,
            price: vue.form.price,
            quantity: vue.form.quantity,
            enableStatus: vue.form.state == true ? 2 : 1,
            description: vue.form.desc
          };

          if (vue.dialogFormNotGoodsAddFlag) {
            _account.addAccountNotGoods(requestParam).then(
              res => {
                _tips.notifyTips(vue, res.msg);
                //更新成功后刷新页面
                vue.getAccountListBySearchTime();
              },
              err => {
                _tips.notifyTips(vue, err.msg);
              }
            );
          } else {
            //编辑操作
            requestParam.id = vue.form.id;
            _account.editNotGoods(requestParam).then(
              res => {
                _tips.notifyTips(vue, res.msg);
                //更新成功后刷新页面
                vue.getAccountListBySearchTime();
              },
              err => {
                _tips.notifyTips(vue, err.msg);
              }
            );
          }
        }
      });
    },

    /**
     * 搜索按钮的点击事件，搜索时间控件的时间范围中的个人账单信息
     */
    getAccountListBySearchTime() {
      this.getStatisticalInfo();
      this.getLineData(true);
      const vue = this;
      const requestParam = {
        timestamps: vue.page.timestamps,
        pageNum: vue.page.pageNum,
        pageSize: vue.page.pageSize
      };
      _account.getAccounts(requestParam).then(
        res => {
          vue.data.accountTableData = res.data.list;
          vue.page.total = res.data.total;
        },
        err => {
          _tips.notifyTips(vue, err.msg);
        }
      );
    },

    /**
     * 5.点击商品分页组件的上一页
     */
    clickProPre() {
      this.page.pageNum--;
      this.getAccountListBySearchTime();
    },

    /**
     * 6.点击商品分页组件的下一页
     */
    clickProNext() {
      this.page.pageNum++;
      this.getAccountListBySearchTime();
    },

    /**
     *7.点击商品分页组件的页码
     */
    clickProPage(page) {
      this.page.pageNum = page;
      this.getAccountListBySearchTime();
    },

    /**
     * 删除一条记录
     */
    deleteAccount(row) {
      const vue = this;
      this.$confirm("此操作将永久删除该条账单, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          const requestParam = {
            id: row.id
          };
          _account.deleteAccount(requestParam).then(
            res => {
              _tips.notifyTips(vue, res.msg);
              //删除成功后刷新页面
              vue.getAccountListBySearchTime();
            },
            err => {
              _tips.notifyTips(vue, err.msg);
            }
          );
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },

    /**
     * 点击表格中的编辑按钮
     */
    editNotGoods(row) {
      const vue = this;
      vue.form.id = row.id; //缓存待编辑记录的id
      vue.form.price = row.price;
      vue.form.quantity = row.quantity;
      vue.form.desc = row.description;
      vue.form.state = row.enableStatus == "未结算" ? false : true;
      vue.dialogFormNotGoodsTitle = "编辑快速记账";
      vue.dialogFormNotGoodsAddFlag = false; //标记为
      vue.dialogFormNotGoodsVisible = true;
    },

    getStatisticalInfo() {
      const vue = this;
      const requestParam = {
        timestamps: vue.page.timestamps
      };
      _account.getStatisticalInfo(requestParam).then(
        res => {
          vue.page.totalCard.content = res.data.totalPrice;
          vue.page.payCard.content = res.data.payedPrice;
          vue.page.unpayCard.content = res.data.unPayPrice;
          vue.page.quantityCard.content = res.data.totalQuantity;
        },
        err => {
          _tips.notifyTips(vue, err.msg);
        }
      );
    },

    //获取搜索搜索时间范围的趋势图数据
    getLineData(totalPrice) {
      const vue = this;
      const requestParam = {
        timestamps: vue.page.timestamps,
        totalPriceData: totalPrice
      };
      _account.getLineData(requestParam).then(
        res => {
          //请求封装的组件的工具类，获取option属性值
          const option = LineChart.getLineChartOption(
            res.data.legendData,
            res.data.xaxisData,
            res.data.seriesData
          );
          let sourceWebChart = vue.$echarts.init(
            document.getElementById("line")
          );
          sourceWebChart.setOption(option);
        },
        err => {
          _tips.notifyTips(vue, err.msg);
        }
      );
    }
  }
};
</script>
<style lang='scss' scoped>
.account-body {
  margin: 0px 10px;
  .accout-time-picker {
    height: 50px;
  }

  .card {
    margin-top: -30px;
    .el-col {
      padding-right: 5px;
      :hover {
        cursor: pointer;
        color: #415065;
      }
    }
  }

  .dialog {
    text-align: left;
    .paymentSate {
      margin-top: 10px;
    }
    .account-quantity {
      width: 221.4px;
    }
  }
}
</style>